﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Net.Mail;
using System.Text;
using Classified.Data;
using Classified.Data.Repositories;
using Classified.Domain.Entities;
using Classified.Web.Helpers;
using Quartz;

namespace Classified.Service
{
    public class EmailService : IJob
    {
        
        public const int NO_OF_MAILS_TO_SEND = 100;
        private readonly ClassifiedContext _context=new ClassifiedContext();

        public void Execute(JobExecutionContext context)
        {
            List<QueuedEmail> lstQueuedEmail =_context.QueuedEmails.Where(x => x.IsSent == false).Take(NO_OF_MAILS_TO_SEND).ToList();
            if (lstQueuedEmail.Count > 0)
            {
                foreach (var queuedEmail in lstQueuedEmail)
                {
                    try
                    {
                        bool emailSendStatus = false;
                        emailSendStatus = EmailHelper.SendEmail(queuedEmail.From, queuedEmail.To, queuedEmail.Subject,
                                                                queuedEmail.Body, queuedEmail.FromName);
                        QueuedEmail objQueuedEmail =
                            _context.QueuedEmails.Find(queuedEmail.Id);
                        if (emailSendStatus)
                        {
                            objQueuedEmail.IsSent = true;
                            objQueuedEmail.SentOnUtc = DateTime.UtcNow;
                        }
                        else
                        {
                            objQueuedEmail.IsSent = false;
                            if (objQueuedEmail.SentTries == null)
                            {
                                objQueuedEmail.SentTries = 1;
                            }
                            else
                            {
                                objQueuedEmail.SentTries += 1;
                            }
                        }
                        _context.Entry(objQueuedEmail).State = EntityState.Modified;
                        _context.SaveChanges();
                        //_context.QueuedEmails.Attach(objQueuedEmail);
                        //_context.SaveChanges();
                    }
                    catch (Exception)
                    {
                        //log error 
                    }
                }
            }
        }
    }
}
